<template>
  <sv-page>
    <sv-nav-bar :options="{ placeholder: false }"></sv-nav-bar>
    <view class="mine">
      <!-- 头部 -->
      <view class="header">
        <image class="header-bg" :src="authInfo?.avatar_file?.url" mode="aspectFill"></image>
        <view class="header-content">
          <view class="flex" @click="onAuth">
            <tn-avatar :url="authInfo?.avatar_file?.url" size="120rpx" shadow>V</tn-avatar>
            <view class="margin-left-sm flex flex-direction justify-around flex-sub">
              <text class="text-xl text-mauve">
                {{ store.hasLogin ? authInfo?.nickname || '未设置昵称' : '登录/注册' }}
              </text>
              <text class="text-lg text-blue">{{ 'Hi 欢迎 ~ ' + getNowTimeName(true) }}</text>
            </view>
            <view class="flex align-center">
              <tn-icon name="right" size="40rpx" />
            </view>
          </view>
          <!-- 数据统计 -->
          <view class="grid col-4 text-center margin-top">
            <view class="padding-top padding-bottom" v-for="item in statisticData" :key="item.name">
              <tn-count-scroll
                font-size="50"
                text-color="#e54d42"
                :value="item?.value || 0"
                :duration="800"
              />
              <text
                class="text-xxl text-red"
                style="vertical-align: top"
                v-if="item.name == '正确率'"
              >
                %
              </text>
              <view class="text-df">{{ item?.name }}</view>
            </view>
          </view>
        </view>
      </view>
      <!-- 常用功能 -->
      <view class="feature card">
        <view class="cu-bar">
          <view class="action sub-title">
            <text class="text-xl text-bold text-blue">常用功能</text>
            <text class="text-ABC text-blue">feature</text>
          </view>
        </view>
        <view class="st-uv-scroll-list">
          <uv-scroll-list :indicator="false">
            <view v-for="item in featureMenu" :key="item.name" @click="onMenu(item)">
              <image class="menu-image" src="/static/logo.png"></image>
              <view class="text-center">{{ item.name }}</view>
            </view>
          </uv-scroll-list>
        </view>
      </view>
      <!-- 列表功能 -->
      <view class="cu-list menu sm-border card-menu sv-list-menu">
        <view class="cu-item arrow" v-for="item in listMenu" :key="item.name" @click="onMenu(item)">
          <view class="content">
            <text class="text-grey" :class="item.icon"></text>
            <text class="text-grey">{{ item.name }}</text>
          </view>
        </view>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow, onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { storageAuth } from '@/utils/pinia-storage'
import { getAuthFromCache, judgeLogin } from '@/utils/sys'
import { getNowTimeName } from '@/utils/util'
import { useSysStore } from '@/store/sys'
import { recordList } from '@/service/api/record'
import clientConfig from '@/client.config'
import { mutations, store } from '@/uni_modules/sv-id-pages/common/store'
import { get, isEmpty } from 'lodash'

onPullDownRefresh(async () => {
  await handleCache()
  await handleInit()

  uni.stopPullDownRefresh()
})

onLoad(() => {})

onShow(() => {
  handleCache()
  handleInit()
})

const navbarHeight = computed(() => {
  const sysConfig = useSysStore().getConfig()
  return sysConfig.navbarHeight + 'px'
})

const authInfo = ref({})
const recordArr = ref({})
const statisticData = ref([
  {
    name: '刷题统计',
    value: 0
  },
  {
    name: '正确统计',
    value: 0
  },
  {
    name: '错误统计',
    value: 0
  },
  {
    name: '正确率',
    value: 0
  }
])

async function handleCache() {
  /**
   * 先进行手动刷新pinia中auth缓存，再获取
   * 因为在单独更新用户头像和昵称等资料时，无法响应式刷新pinia中auth数据
   * 从而造成未能实时刷新更改后的个人资料，故需要手动调用storageAuth进行更新
   */
  storageAuth()
  authInfo.value = await getAuthFromCache()
  // console.log('==== authInfo.value :', authInfo.value)
}

async function handleInit() {
  if (!store.hasLogin) return
  const recordRes = await recordList({
    user_id: store.userInfo._id
  })
  recordArr.value = get(recordRes, 'data[0]')
  // console.log('==== recordArr.value :', recordArr.value)
  if (isEmpty(recordArr.value)) return

  // 数据统计展示
  const { correct_num, error_num } = recordArr.value
  statisticData.value = [
    {
      name: '刷题统计',
      value: correct_num + error_num
    },
    {
      name: '正确统计',
      value: correct_num
    },
    {
      name: '错误统计',
      value: error_num
    },
    {
      name: '正确率',
      value:
        correct_num + error_num == 0
          ? 0
          : Math.round((correct_num / (correct_num + error_num)) * 100).toFixed(0)
    }
  ]
}

function onAuth() {
  if (!store.hasLogin) {
    mutations.logout()
  } else {
    uni.navigateTo({
      url: '/uni_modules/sv-id-pages/pages/userinfo/userinfo'
    })
  }
}

const featureMenu = clientConfig.staticMenu.featureMenu
const listMenu = clientConfig.staticMenu.listMenu

function onMenu(e) {
  const WHITE_LIST = ['/pages/mine/about/about', '/pages/mine/setting/setting']
  if (!WHITE_LIST.includes(e.url)) {
    // 判断登录
    const hasLogin = judgeLogin()
    // 未登录不予操作
    if (!hasLogin) return
  }
  uni.navigateTo({ url: e.url })
}
</script>

<style lang="scss">
.mine {
  height: 100%;
  position: relative;

  @include useTheme {
    background-color: getTheme('sv-background-color');
    color: getTheme('sv-text-color');
  }

  .header {
    width: 100%;
    position: relative;

    .header-bg {
      width: 100%;
      height: calc(360rpx + v-bind(navbarHeight));
      filter: blur(30rpx);
      opacity: 0.8;
    }

    .header-content {
      position: absolute;
      top: v-bind(navbarHeight);
      left: 0;
      right: 0;
      bottom: 0;
      margin: 30rpx;
    }
  }

  .feature {
    margin: 0 30rpx;
    position: relative;
    padding-bottom: 10rpx;

    .st-uv-scroll-list {
      padding: 0 10px;
    }

    .menu-image {
      width: 100rpx;
      height: 100rpx;
      margin: 0 10px;
    }
  }

  .sv-list-menu {
    margin: 30rpx;

    .cu-item {
      @include useTheme {
        background-color: getTheme('sv-background-highlight-color');
      }
    }
  }
}
</style>
